"""Bag转换线程模块
实现Bag文件转换的后台处理线程
"""

import asyncio
from pathlib import Path
from PySide2.QtCore import QThread, Signal
from gglobal import logger
from apis.ros1.readbagchange import RosBagConverter
from mooetoolapp.handlercore.language_manager import LanguageManager


class BagChangeThread(QThread):
    """Bag转换线程类"""
    
    # 定义信号
    conversion_finished = Signal(bool, str)  # 转换完成信号 (成功/失败, 消息)
    
    def __init__(self, input_bag_path, output_bag_path, target_topics=None, custom_msg_path=None):
        super().__init__()
        self.input_bag_path = Path(input_bag_path)
        self.output_bag_path = Path(output_bag_path)
        self.target_topics = target_topics
        self.custom_msg_path = custom_msg_path
        self.converter = None
        self._is_cancelled = False
        self.language_manager = LanguageManager()
        
    def run(self):
        """线程主执行函数"""
        try:
            logger.info(f"开始Bag转换: {self.input_bag_path} -> {self.output_bag_path}")
            
            # 重置取消状态
            self._is_cancelled = False
            
            # 创建转换器
            self.converter = RosBagConverter(
                bag_path=self.input_bag_path,
                output_bag_path=self.output_bag_path,
                target_topics=self.target_topics,
                custom_msg_path=self.custom_msg_path
            )
            

            
            # 运行异步转换
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            
            try:
                loop.run_until_complete(self.converter.process_bag())
                
                if not self._is_cancelled:
                    success_msg = self.language_manager.get_text("bag_convert_success_message", category="constants").format(
                        input_file=self.input_bag_path.name,
                        output_file=self.output_bag_path.name
                    )
                    self.conversion_finished.emit(True, success_msg)
                    logger.info("Bag转换成功完成")
                else:
                    cancel_msg = self.language_manager.get_text("bag_convert_cancelled_message", category="constants")
                    self.conversion_finished.emit(False, cancel_msg)
                    logger.info("Bag转换被用户取消")
                    
            finally:
                loop.close()
                
        except Exception as e:

            error_msg = self.language_manager.get_text("bag_convert_error_message", category="constants").format(error=str(e))
            logger.error(f"Bag转换失败: {e}", exc_info=True)
            self.conversion_finished.emit(False, error_msg)
            

        
    def cancel_conversion(self):
        """取消转换"""
        self._is_cancelled = True
        if self.converter:
            self.converter.cancel_conversion()
        logger.info("请求取消Bag转换")
        # 注意：不在这里发射conversion_finished信号，让run方法中的逻辑处理
        
    def is_cancelled(self):
        """检查是否已取消"""
        return self._is_cancelled